import os, sys

sys.path.insert(0, os.path.expanduser('~') + '/lib/python')

from mylib.mygl import *


class Textures(object):
    texes = {}
    PIL = 1
    PG = 2

    def __init__(self, lib=1):
        self.use_lib = lib

    def __del__(self):
        self.clear()

    # noinspection PyBroadException
    def load(self, key, filename, auto_split=False, width=None, height=None, alpha=True, detail=5):
        try:
            if self.use_lib == Textures.PG: image = pygame.image.load(filename)
            elif self.use_lib == Textures.PIL: image = Image.open(filename)
            else: return False, 0
        except: return False, 0

        if self.use_lib == Textures.PG:
            if image.get_alpha() and alpha: alpha = True
            else: alpha = False
            if alpha: image = image.convert_alpha()
            else: image = image.convert()
            image_w, image_h = image.get_size()
        else:  # if self.use_lib == Textures.PIL:
            if image.mode == 'RGBA' and alpha: alpha = True
            else: alpha = False
            image_w, image_h = image.size
            print(filename, image.mode, image.size)
        w, h = image_w, image_h
        if auto_split:
            if image_w > image_h: w, h = image_h, image_h
            else: w, h = image_w, image_w

        if height is not None: h = height
        if width is not None: w = width
        sy = 0
        idx = 0
        while sy < image_h:
            sx = 0
            while sx < image_w:
                if self.use_lib == Textures.PG:
                    sub_image = image.subsurface((sx, sy, w, h))
                    pixels = pygame.image.tostring(sub_image, "RGBA" if alpha else "RGB", True)
                else:
                    sub_image = image.crop((sx, sy, sx + w, sy + h))
                    print(filename, idx, sub_image.size, sub_image.mode)
                    pixels = sub_image.tostring("raw", "RGBA" if alpha else "RGB", 0, -1)
                tex_id, _, _ = load_texture(pixels=pixels, width=w, height=h, alpha=alpha, detail=detail)
                self.texes[key + ',' + str(idx)] = tex_id, alpha

                idx += 1
                sx += w
            sy += h
        return True, idx

    def bind(self, key, idx=0):
        key = key + ',' + str(idx)
        if key in self.texes.keys():
            glEnable(GL_TEXTURE_2D)
            tid, alpha = self.texes[key]
            if alpha: glEnable(GL_BLEND)
            else: glDisable(GL_BLEND)
            glBindTexture(GL_TEXTURE_2D, tid)
            return True
        else:
            return False

    def get(self, key, idx=0):
        key = key + ',' + str(idx)
        if key in self.texes.keys(): return self.texes[key]
        else: return 0, 1

    def count(self, key):
        cnt = 0
        for k in self.texes.keys():
            if k.startswith(key): cnt += 1
        return cnt

    def clear(self):
        for key in self.texes.keys():
            glDeleteTextures(self.texes[key])

